<?php
namespace plugin\ky_shouyin\app\controller\front;

use support\Request;
use support\Db;
use support\Log;
use plugin\sms\api\Sms;
use plugin\ky_shouyin\app\controller\BaseController;

class CashierController extends BaseController
{
    /**
     * 收银台首页
     */
    public function index()
    {
        return $this->view('front/cashier/index');
    }
    
    /**
     * 获取商品分类
     */
    public function categories()
    {
        $categories = Db::table('ky_goods_category')
            ->where('status', 1)
            ->orderBy('sort', 'asc')
            ->get();
            
        return json(['code' => 0, 'msg' => 'ok', 'data' => $categories]);
    }
    
    /**
     * 获取商品列表
     */
    public function goods(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $categoryId = $request->get('category_id', '');
        
        $query = Db::table('ky_goods')->where('status', 1);
        
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('code', 'like', "%{$keyword}%");
            });
        }
        
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }
        
        $goods = $query->get();
        return json(['code' => 0, 'msg' => 'ok', 'data' => $goods]);
    }
    
    /**
     * 获取会员信息
     */
    public function getMember(Request $request)
    {
        $keyword = $request->get('keyword');
        if (!$keyword) {
            return json(['code' => 1, 'msg' => '请输入会员卡号或手机号']);
        }

        $member = Db::table('ky_member')
            ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
            ->where(function ($query) use ($keyword) {
                $query->where('ky_member.card_no', $keyword)
                    ->orWhere('ky_member.phone', $keyword);
            })
            ->where('ky_member.status', 1)
            ->select('ky_member.*', 'ky_member_level.name as level_name')
            ->first();

        if (!$member) {
            return json(['code' => 1, 'msg' => '会员不存在']);
        }

        return json(['code' => 0, 'msg' => 'ok', 'data' => $member]);
    }

    /**
     * 发送消费验证码
     */
    public function sendVerifyCode(Request $request)
    {
        $memberId = $request->post('member_id');
        
        try {
            // 获取会员信息
            $member = Db::table('ky_member')
                ->where('id', $memberId)
                ->first();
                
            if (!$member) {
                return json(['code' => 1, 'msg' => '会员不存在']);
            }
            
            // 生成6位随机验证码
            $code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
            
            // 保存验证码到session
            session([
                'consume_verify_code_' . $memberId => [
                    'code' => $code,
                    'expire_time' => time() + 300 // 5分钟有效期
                ]
            ]);
            
            // 发送短信
            $templateParams = [
                'code' => $code,
                'time' => 5
            ];
            
            Sms::sendByTag($member->phone, 'ky_consume_verify', $templateParams, ['aliyun']);
            
            return json(['code' => 0, 'msg' => '验证码已发送']);
            
        } catch (\Exception $e) {
            Log::error('发送消费验证码失败：' . $e->getMessage());
            return json(['code' => 1, 'msg' => '发送失败：' . $e->getMessage()]);
        }
    }

    /**
     * 提交订单
     */
    public function submitOrder(Request $request)
    {
        
        try {
            
            // 获取请求数据
            $data = json_decode($request->rawBody(), true);
            
            // 基础参数验证
            if (empty($data['goods']) || !is_array($data['goods'])) {
                return json(['code' => 1, 'msg' => '请选择商品']);
            }
            
            if (!isset($data['payment_method'])) {
                return json(['code' => 1, 'msg' => '请选择支付方式']);
            }
            
            // 金额验证
            $totalAmount = floatval($data['total_amount'] ?? 0);
            $discountAmount = floatval($data['discount_amount'] ?? 0);
            $actualAmount = floatval($data['actual_amount'] ?? 0);
            
            if ($totalAmount <= 0) {
                return json(['code' => 1, 'msg' => '订单金额异常']);
            }
            
            if ($actualAmount <= 0) {
                return json(['code' => 1, 'msg' => '实付金额异常']);
            }
            
            // 支付方式转换
            $payTypeMap = [
                'cash' => 2,    // 现金支付
                'wechat' => 1,  // 微信支付
                'alipay' => 1,  // 支付宝支付
                'balance' => 3  // 余额支付
            ];
            
            $payType = $payTypeMap[$data['payment_method']] ?? 1;
            
            // 余额支付验证
            if ($data['payment_method'] === 'balance') {
                if (empty($data['member_card_no'])) {
                    return json(['code' => 1, 'msg' => '请先选择会员']);
                }
                
                // 通过会员卡号关联查询会员信息
                $member = Db::table('ky_member')
                    ->join('ky_member_card', 'ky_member.id', '=', 'ky_member_card.member_id')
                    ->where('ky_member_card.card_no', $data['member_card_no'])
                    ->where('ky_member.status', 1)
                    ->where('ky_member_card.status', 1)
                    ->select('ky_member.*', 'ky_member_card.card_no')
                    ->first();
                    
                if (!$member) {
                    return json(['code' => 1, 'msg' => '会员不存在或已禁用']);
                }
                if ($member->balance < $actualAmount) {
                    return json(['code' => 1, 'msg' => '会员余额不足，当前余额：' . $member->balance]);
                }
                
                $data['user_id'] = $member->id;

                 // 验证验证码
                $verifyInfo = session('consume_verify_code_' . $data['user_id']);
                if (!$verifyInfo || 
                    $verifyInfo['code'] !== $data['verify_code'] || 
                    $verifyInfo['expire_time'] < time()) {
                    return json(['code' => 1, 'msg' => '验证码错误或已过期']);
                }
                
                // 验证通过,清除验证码
                session(['consume_verify_code_' . $data['user_id'] => null]);
                
              
            }
            
            try {
                Db::beginTransaction();
                
                // 创建订单（初始状态为未支付）
                $orderId = Db::table('ky_order')->insertGetId([
                    'order_no' => 'DD' . date('YmdHis') . rand(1000, 9999),
                    'user_id' => $data['user_id'] ?? null,
                    'store_id' => session('user.store_id'),
                    'staff_id' => session('user.id'),
                    'total_amount' => $totalAmount,
                    'paid_amount' => $actualAmount,
                    'discount_amount' => $discountAmount,
                    'points_used' => 0,
                    'points_deduction_amount' => 0,
                    'points_earned' => intval($actualAmount),
                    'status' => 0,
                    'remark' => $data['remark'] ?? '',
                    'is_pay' => 0,
                    'pay_type' => $payType,
                    'order_type' => 'retail',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                
                // 创建订单商品
                foreach ($data['goods'] as $item) {
                    // 验证商品是否存在
                    $goods = Db::table('ky_goods')
                        ->where('id', $item['goods_id'])
                        ->where('status', 1)
                        ->first();
                        
                    if (!$goods) {
                        throw new \Exception('商品不存在或已下架：' . $item['goods_name']);
                    }
                    
                    // 创建订单商品记录
                    Db::table('ky_order_goods')->insert([
                        'order_id' => $orderId,
                        'goods_id' => $item['goods_id'],
                        'goods_name' => $item['goods_name'],
                        'goods_price' => $item['price'],
                        'quantity' => $item['quantity'],
                        'total_amount' => $item['subtotal'],
                        'discount_amount' => 0,
                        'final_amount' => $item['subtotal'],
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    // 更新商品销量，使用 increment 方法
                    $result = Db::table('ky_goods')
                        ->where('id', $item['goods_id'])
                        ->increment('sales_count', (int)$item['quantity']);
                        
                    if (!$result) {
                        throw new \Exception('更新商品销量失败');
                    }
                }
                
                // 根据支付方式处理订单
                if ($payType == 2) { // 现金支付
                    // 直接更新订单状态为已支付
                    Db::table('ky_order')->where('id', $orderId)->update([
                        'status' => 1,
                        'is_pay' => 1,
                        'payment_time' => date('Y-m-d H:i:s')
                    ]);
                } 
                elseif ($payType == 3 && !empty($data['user_id'])) { // 余额支付
                    // 更新会员余额
                    $updateResult = Db::table('ky_member')
                        ->where('id', $data['user_id'])
                        ->where('balance', '>=', $actualAmount)
                        ->decrement('balance', $actualAmount);
                        
                    if (!$updateResult) {
                        throw new \Exception('余额扣除失败，请重试');
                    }
                    
                    // 记录余额变动
                    Db::table('ky_member_balance_log')->insert([
                        'member_id' => $data['user_id'],
                        'order_id' => $orderId,
                        'amount' => -$actualAmount,
                        'type' => 2,
                        'before_balance' => $member->balance,
                        'after_balance' => $member->balance - $actualAmount,
                        'operator_id' => session('user.id'),
                        'store_id' => session('user.store_id'),
                        'remark' => '订单支付',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    // 更新订单状态为已支付
                    Db::table('ky_order')->where('id', $orderId)->update([
                        'status' => 1,
                        'is_pay' => 1,
                        'payment_time' => date('Y-m-d H:i:s')
                    ]);
                     // 发送充值短信通知
                     try {
                        // 准备短信模板变量
                        $templateParams = [
                            'name' => $member->name,
                            'money' => $actualAmount,
                            'blance' => $member->balance - $actualAmount
                        ];
                        $to = $member->phone;
                        $tagName = 'ky_user_xf';
                        $gateway = 'aliyun';
                        Sms::sendByTag($to, $tagName, $templateParams, [$gateway]);
                       
                    } catch (\Exception $e) {
                        // 记录短信发送失败日志，但不影响充值业务
                        Log::error('充值短信发送失败：' . $e->getMessage());
                    }
                }
                
                Db::commit();
                return json(['code' => 0, 'msg' => '下单成功', 'data' => ['order_id' => $orderId]]);
            } catch (\Exception $e) {
                Db::rollBack();
                return json(['code' => 1, 'msg' => '下单失败：' . $e->getMessage()]);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '提交失败：' . $e->getMessage()]);
        }
    }

    /**
     * 搜索会员
     */
    public function searchMember(Request $request)
    {
        $keyword = $request->get('keyword');
        if (!$keyword) {
            return json(['code' => 1, 'msg' => '请输入会员卡号或手机号']);
        }
    
        $member = Db::table('ky_member')
            ->leftJoin('ky_member_card', 'ky_member.id', '=', 'ky_member_card.member_id')
            ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
            ->where(function ($query) use ($keyword) {
                $query->where('ky_member_card.card_no', $keyword)
                    ->orWhere('ky_member.phone', $keyword);
            })
            ->where('ky_member.status', 1)
            ->where('ky_member_card.status', 1)
            ->select('ky_member.*', 'ky_member_card.card_no', 'ky_member_level.name as level_name')
            ->first();
    
        if (!$member) {
            return json(['code' => 1, 'msg' => '会员不存在']);
        }
    
        return json(['code' => 0, 'msg' => 'ok', 'data' => $member]);
    }
}